package com.isoft.service;

import com.isoft.entity.Authority;
import com.isoft.entity.Customer;
import com.isoft.repository.AuthorityService;
import com.isoft.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiuGaoMing
 * @version 1.0
 * @description:
 * @date 2024/5/17 9:17
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private CustomerService customerService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = customerService.getCustomer(username);
        List<Authority> authorityList = customerService.getCustomerAuthorities(username);
//        对用户权限进行封装
        List<SimpleGrantedAuthority> list = authorityList
                .stream()
                .map(authority -> new SimpleGrantedAuthority(authority.getAuthority()))
                .collect(Collectors.toList());
        if(customer !=null){
            UserDetails userDetails = new User(customer.getUsername(), customer.getPassword(), list);
            return userDetails;
        }else {
            throw new UsernameNotFoundException("用户不存在");
        }
    }
}
